package fun.coding.leetcode;

import java.util.Stack;

public class EvaluateReversePolishNotation {

	public static void main(String[] args) {
		EvaluateReversePolishNotation ins = new EvaluateReversePolishNotation();
		
		String[] test1 = {"4","3","/"};
		System.out.println(ins.evalRPN(test1));
	}
	
	public int evalRPN(String[] tokens) {
		if (tokens == null || tokens.length == 0) return 0;
		
		Stack<String> stack = new Stack<String>();
		
		for (String s : tokens) {
			if (isOperand(s)) {
				int a1 = Integer.parseInt(stack.pop());
				int a2 = Integer.parseInt(stack.pop());
				int res = 0;
				
				switch (s){
				case "+":
					res = a1 + a2;
					break;
				case "-":
					res = a2 - a1;
					break;
				case "*":
					res = a2 * a1;
					break;
				case "/":
					assert a1 != 0;
					res = a2 / a1;
					break;
				}
				stack.push(String.valueOf(res));
			} else {
				stack.push(s);
			}
		}
		return Integer.parseInt(stack.pop());
	}
	
	private boolean isOperand(String s) {
		return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
	}
}
